/*
   function: 保存网络上传失败的数据，供后续补传操作
   warn:  非线程安全
   brief: 采用循环缓冲区的思想，补传文件会设定最大补传条数，然后循环覆盖数据
*/
#ifndef __HISTORYRECORD_H_
#define __HISTORYRECORD_H_

#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "log.h"

#define HISTORY_RECORD_LEN (1016)
#define TAG_STR "TAG"
#define VERSION_STR "Version1.1"
//固定256字节
typedef struct HistoryFileHeader_t
{
   unsigned int header; //0x55aa55aa
   char version[12]; //"version1.1"
   char tag[4] ;//固定"TAG\0"
   unsigned int maxrecord; //最大可存储的条数
   unsigned int readindex; //当前读取的索引
   unsigned int writeindex; //当前写的索引
   unsigned int onerecordbytes;//每条记录所占字节
   char reverse[220]; 

}HistoryFileHeader;

//每条固定最大1k
typedef struct HistoryRecordHeader_t
{
   unsigned int header; //0x55aa55aa
   unsigned int datalen; //数据长度
   unsigned char valid; //0无效数据 1有效数据
   unsigned char data[HISTORY_RECORD_LEN];  //数据
}HistoryRecordHeader;

class CHistoryRecord
{
    public:
      CHistoryRecord();
     ~CHistoryRecord();
      /*
          有文件则打开，没有则创建
          失败返回NULL
      */
      HistoryFileHeader   *HistoryInit(const char *filename, unsigned short maxrecord=1000);
      int HistorySetValid(unsigned char valid, int writeindex);
      int HistoryWrite(char *historydata, int datalen, int writeindex);
      int HistoryAdd(char *historydata, int datalen);
      int HistoryRead(char *readdata);
      int HistoryRead(char *readdata, int recordcount);
      int HistoryRemainCount();

    private:
      int filefd;
      HistoryFileHeader *fileheader;
      int HistorySyncFileHeader();

};




#endif